const tbody = document.querySelector('tbody');

// 获取分数方法
async function getScore() {
    const res = await axios({
        url: '/score/list',
        // headers: {
        //     Authorization: localStorage.getItem('token')
        // }
    })
    // console.log(res.data.data);
    let html = ''
    for (const key in res.data.data) {
        const { name, score } = res.data.data[key]
        html += `<tr>
        <th scope="row">${key}</th>
        <td>${name}</td>
        <td class="score" data-stu_id='${key}' data-batch='1'>${score[0]}</td>
        <td class="score" data-stu_id='${key}' data-batch='2'>${score[1]}</td>
        <td class="score" data-stu_id='${key}' data-batch='3'>${score[2]}</td>
        <td class="score" data-stu_id='${key}' data-batch='4'>${score[3]}</td>
        <td class="score" data-stu_id='${key}' data-batch='5'>${score[4]}</td>
      </tr>`
    }
    tbody.innerHTML = html
}

getScore();
// 封装函数
// 修改分数
tbody.addEventListener('dblclick', e => {
    const target = e.target
    // console.log(target);
    if (target.classList.contains('score')) {
        const input = document.createElement('input');
        input.type = "text";
        input.value = target.innerHTML;
        target.appendChild(input);
        // input 获取焦点
        input.focus()

        async function changeScore() {
            const { stu_id, batch } = target.dataset       //自定义属性的值
            const score = input.value                      // 获取input输入的值

            const res = await axios({
                url: '/score/entry',
                method: 'post',
                data: {
                    stu_id,
                    batch,
                    score
                }
            })
            // 判断若成功输出提示
            if (res.data.code === 0) {
                toastr.success(res.data.message, "恭喜")
                getScore()
            }
        }

        input.addEventListener('blur', changeScore)
        input.addEventListener('keyup', e => {
            if (e.key === 'Enter') {
                input.removeEventListener('blur', changeScore)
                changeScore(target, input);
                // input.blur();
            }
        })
    }
})